#!/usr/bin/env python2

import os
import sys
import socket
import time
import subprocess
import fcntl
import types
import errno
import getopt
import random
import threading
import traceback
import json
import urllib2

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
#import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

from daemon import Daemon
from config import Config
from utils import Exp, _dmsg, _dwarn, _derror, _str2dict, _getrack, _exec_pipe1

config = Config()

def handler_exec(path):
    if (path[0] == '/'):
        path = path[1:]

    path = urllib2.unquote(path)
    print ("exec:" + path)
    if ((not path.startswith('lich.')) and (not path.startswith(config.home + '/lich/admin'))):
        return {'errno' : errno.EPERM,
                'stdout' : '',
                'stderr' : "not allow '%s'" % (path)}

    args = path.split(' ')
    cmd = []
    for i in args:
        cmd.append(i)

    print(cmd)

    if (cmd[0] == 'lich.node'):
        cmd.append('--ttyonly')

    try:
        out, err = _exec_pipe1(cmd, 0, False)
        _errno = 0;
    except Exp, e:
        _derror("handler %s fail" % (path))
        _errno = e.errno
        out = e.out
        err = e.err

    return {'errno' : _errno,
           'stdout' : out,
           'stderr' : err}

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            res = handler_exec(self.path)
        except:
            _derror("handler %s fail" % (self.path))
            traceback.print_exc()
            return

        self.send_response(200)
        self.end_headers()
        try:
            self.wfile.write(json.dumps(res))
            self.wfile.write('\n')
        except:
            _derror("write %s error" % (str(self.wfile)))
            pass
        return

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

class Mds_Shell(Daemon):
    def __init__(self):
        self.config = Config()
        os.system('mkdir -p ' + self.config.home + '/tmp')
        os.system('mkdir -p ' + self.config.home + '/log')
        pidfile = '/var/run/fusionstack_shell.pid'
        log = self.config.home + '/log/fusionstack_shell.log'
        os.system('touch ' + log)
        super(Mds_Shell, self).__init__(pidfile, '/dev/null', log, log, 'mds shell')

    def run(self):
        server = ThreadedHTTPServer(('', 27901), Handler)
        server.serve_forever()

def usage():
    print ("usage:")
    print (sys.argv[0] + " --start")
    print (sys.argv[0] + " --stop")
    print (sys.argv[0] + " --test")
    print (sys.argv[0])

def main():
    op = ''
    ext = None
    try:
        opts, args = getopt.getopt(
                sys.argv[1:], 
            'h', ['start', 'stop', 'help', 'test']
                )
    except getopt.GetoptError, err:
        print str(err)
        usage()

    mds_shell = Mds_Shell()
    for o, a in opts:
        if o in ('--help'):
            usage()
            exit(0)
        elif (o == '--start'):
            op = o
            mds_shell.start()
        elif (o == '--stop'):
            op = o
            mds_shell.stop()
        elif (o == '--test'):
            mds_shell.run()
        else:
            assert False, 'oops, unhandled option: %s, -h for help' % o
            exit(1)

if __name__ == '__main__':
    if (len(sys.argv) == 1):
        usage()
    else:
        main()
